package com.zx.baofu.alcohol.service.impl;

import com.zx.baofu.alcohol.service.FileService;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@ConfigurationProperties(prefix = "file-upload")
@Data
@Log4j2
public class FileServiceImpl implements FileService {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    private String baseDir;
    private String baseUrl;

    @Override
    public String upload(MultipartFile file) {
        log.info("调用了图片上传方法");
        String dateDirs = LocalDate.now().format(DATE_TIME_FORMATTER);
        String uuidDir = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = file.getOriginalFilename();
        String pathSuffix = "/" + dateDirs + "/" + uuidDir + "/" + originalFilename;
        File destination = new File(baseDir + pathSuffix);
        boolean b = destination.getParentFile().mkdirs();
        log.info("destination: "+ destination.getParentFile());
        log.info("创建路径成功："+ b);
        try {
            file.transferTo(new File(baseDir + pathSuffix));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        log.info("baseUrl + pathSuffix: "+ baseUrl + pathSuffix);
        return baseUrl + pathSuffix;
    }
}
